#!/bin/bash

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 版本信息
VERSION="1.0.0"

# 要部署的模块列表
MODULES=(
  "doubao-gateway"
  "doubao-auth"
  "doubao-user"
  "doubao-device"
  "doubao-chat"
  "doubao-file"
  "doubao-wechat"
  "doubao-hardware"
)

# 核心服务列表
CORE_SERVICES=(
  "doubao-gateway"
  "doubao-auth"
  "doubao-user"
  "doubao-chat"
)

# 次要服务列表
OTHER_SERVICES=(
  "doubao-device"
  "doubao-file"
  "doubao-wechat"
  "doubao-hardware"
)

# 基础设施服务列表
INFRA_SERVICES=(
  "nacos"
  "redis"
  "mysql"
  "rmqnamesrv"
  "rmqbroker"
)

# 显示帮助信息
show_help() {
  echo -e "${BLUE}豆包云微服务一体化部署工具 v${VERSION}${NC}"
  echo -e "${YELLOW}用法:${NC} $0 [选项]"
  echo
  echo -e "${YELLOW}选项:${NC}"
  echo -e "  ${GREEN}help${NC}      显示此帮助信息"
  echo -e "  ${GREEN}build${NC}     只构建项目 (Maven 构建)"
  echo -e "  ${GREEN}deploy${NC}    只部署项目 (使用已构建的 JAR 文件)"
  echo -e "  ${GREEN}all${NC}       执行完整的构建和部署流程 (默认)"
  echo -e "  ${GREEN}setup${NC}     初始化项目结构 (创建目录和 Dockerfile)"
  echo -e "  ${GREEN}status${NC}    检查服务状态"
  echo -e "  ${GREEN}logs${NC}      查看服务日志"
  echo
  echo -e "${YELLOW}示例:${NC}"
  echo -e "  $0                  # 执行默认的完整流程"
  echo -e "  $0 build            # 只执行构建"
  echo -e "  $0 deploy           # 只执行部署"
  echo -e "  $0 logs doubao-gateway  # 查看网关服务的日志"
}

# 检查环境
check_environment() {
  echo -e "${BLUE}=== 检查环境 ===${NC}"

  # 检查 Docker
  if ! command -v docker &> /dev/null; then
    echo -e "${RED}错误: Docker 未安装${NC}"
    exit 1
  fi

  # 检查 Docker 是否运行
  if ! docker info &> /dev/null; then
    echo -e "${RED}错误: Docker 未运行${NC}"
    echo -e "${YELLOW}请先启动 Docker 服务${NC}"
    exit 1
  fi

  # 检查 Docker Compose
  if ! command -v docker-compose &> /dev/null; then
    echo -e "${RED}错误: Docker Compose 未安装${NC}"
    exit 1
  fi

  echo -e "${GREEN}环境检查通过${NC}"
}

# 检查基础设施服务
check_infra_services() {
  echo -e "${BLUE}=== 检查基础设施服务 ===${NC}"

  services_running=true
  for service in "${INFRA_SERVICES[@]}"; do
    if docker ps | grep -q $service; then
      echo -e "${GREEN}✓ $service 服务正在运行${NC}"
    else
      echo -e "${RED}✗ $service 服务未运行${NC}"
      services_running=false
    fi
  done

  if [ "$services_running" = false ]; then
    echo -e "${YELLOW}有基础服务未运行，是否继续? (y/n): ${NC}"
    read -p "" continue_deploy
    if [ "$continue_deploy" != "y" ]; then
      echo -e "${RED}操作已取消${NC}"
      exit 0
    fi
  fi
}

# 初始化项目结构
setup_project() {
  echo -e "${BLUE}=== 初始化项目结构 ===${NC}"

  # 检查 docker-compose.yml 是否存在
  if [ ! -f "docker-compose.yml" ]; then
    echo -e "${YELLOW}docker-compose.yml 不存在，正在创建...${NC}"
    cat > docker-compose.yml << EOF
version: '3'

services:
EOF

    # 为每个模块创建 docker-compose 配置
    for module in "${MODULES[@]}"; do
      is_core=false
      memory="225M"
      cpus="0.7"
      port="${module: -1}"

      if [[ " ${CORE_SERVICES[@]} " =~ " ${module} " ]]; then
        is_core=true
        memory="400M"
        cpus="1"
      fi

      # 基于模块名称确定端口
      case "$module" in
        "doubao-gateway") port="8001" ;;
        "doubao-auth") port="8081" ;;
        "doubao-user") port="8082" ;;
        "doubao-device") port="8083" ;;
        "doubao-chat") port="8084" ;;
        "doubao-file") port="8085" ;;
        "doubao-wechat") port="8086" ;;
        "doubao-hardware") port="8087" ;;
      esac

      # 添加服务配置
      cat >> docker-compose.yml << EOF

  # $(if [ "$is_core" = true ]; then echo "核心服务"; else echo "次要服务"; fi) - $module
  $module:
    build:
      context: ./$module
      dockerfile: Dockerfile
    container_name: $module
    ports:
      - "$port:$port"
    environment:
      - JAVA_OPTS=-Xms$(if [ "$is_core" = true ]; then echo "150m -Xmx400m"; else echo "80m -Xmx225m"; fi) -XX:+UseG1GC -XX:MaxGCPauseMillis=200
      - NACOS_HOST=nacos
      - REDIS_HOST=redis
      - MYSQL_HOST=mysql
      - ROCKETMQ_HOST=rmqnamesrv
    deploy:
      resources:
        limits:
          cpus: '$cpus'
          memory: '$memory'
    extra_hosts:
      - "nacos:172.17.0.1"
      - "redis:172.17.0.1"
      - "mysql:172.17.0.1"
      - "rmqnamesrv:172.17.0.1"
      - "rmqbroker:172.17.0.1"
    restart: unless-stopped
    network_mode: "bridge"
EOF
    done

    echo -e "${GREEN}docker-compose.yml 已创建${NC}"
  else
    echo -e "${GREEN}docker-compose.yml 已存在${NC}"
  fi

  # 为每个模块创建目录和 Dockerfile
  for module in "${MODULES[@]}"; do
    # 创建目录
    if [ ! -d "$module" ]; then
      mkdir -p "$module"
      echo -e "${GREEN}创建目录: $module${NC}"
    fi

    # 创建 Dockerfile
    dockerfile="$module/Dockerfile"
    if [ ! -f "$dockerfile" ]; then
      cat > "$dockerfile" << EOF
FROM openjdk:17

# 设置时区为上海时间
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/\$TZ /etc/localtime && echo \$TZ > /etc/timezone

# 设置工作目录
WORKDIR /app

# 复制模块的JAR文件到容器
COPY target/${module}-0.0.1-SNAPSHOT.jar app.jar

# 设置容器启动命令
ENTRYPOINT ["sh", "-c", "java \${JAVA_OPTS} -jar /app/app.jar"]
EOF
      echo -e "${GREEN}创建 Dockerfile: $dockerfile${NC}"
    fi
  done

  echo -e "${GREEN}项目结构初始化完成${NC}"
}

# 使用Docker容器构建项目
build_project() {
  echo -e "${BLUE}=== 构建项目 ===${NC}"

  # 询问是否需要清理
  echo -e "${YELLOW}是否清理现有构建文件? (y/n): ${NC}"
  read -p "" clean_build

  # 构建命令
  if [ "$clean_build" = "y" ]; then
    maven_cmd="mvn clean install test"
  else
    maven_cmd="mvn install test"
  fi

  # 使用Docker容器执行Maven构建
  echo -e "${YELLOW}使用Docker容器执行Maven构建...${NC}"
  echo -e "${YELLOW}命令: $maven_cmd${NC}"

  docker run -it --rm \
    -v "$(pwd)":/usr/src/mymaven \
    -v "$HOME/.m2":/root/.m2 \
    -w /usr/src/mymaven \
    maven:3.8-openjdk-17 \
    $maven_cmd

  # 检查构建结果
  if [ $? -ne 0 ]; then
    echo -e "${YELLOW}构建过程出现错误。是否继续部署已成功构建的模块? (y/n): ${NC}"
    read -p "" continue_deploy
    if [ "$continue_deploy" != "y" ]; then
      echo -e "${RED}部署已取消${NC}"
      exit 1
    fi
  else
    echo -e "${GREEN}项目构建成功${NC}"
  fi

  # 检查生成的 JAR 文件
  echo -e "${YELLOW}检查生成的 JAR 文件...${NC}"
  available_modules=()

  for module in "${MODULES[@]}"; do
    jar_files=($(find "./${module}/target" -name "*.jar" 2>/dev/null | grep -v "original"))

    if [ ${#jar_files[@]} -gt 0 ]; then
      jar_name=$(basename "${jar_files[0]}")
      jar_size=$(du -h "${jar_files[0]}" | cut -f1)
      echo -e "${GREEN}✓ ${module}: ${jar_name} (${jar_size})${NC}"

      # 更新 Dockerfile 使用正确的 JAR 文件名
      if [ "$jar_name" != "${module}-0.0.1-SNAPSHOT.jar" ]; then
        sed -i "s|COPY target/.*\.jar|COPY target/${jar_name}|" "./${module}/Dockerfile"
        echo -e "${YELLOW}  更新 Dockerfile 使用: ${jar_name}${NC}"
      fi

      # 添加到可部署模块列表
      available_modules+=("$module")
    else
      echo -e "${RED}✗ ${module}: 未找到 JAR 文件${NC}"
    fi
  done

  # 将可部署模块保存到临时文件以供部署函数使用
  echo "${available_modules[@]}" > /tmp/available_modules.txt
}

# 部署项目
deploy_project() {
  echo -e "${BLUE}=== 部署项目 ===${NC}"

  # 检查是否有可用模块列表
  if [ -f "/tmp/available_modules.txt" ]; then
    read -r -a deploy_modules <<< "$(cat /tmp/available_modules.txt)"
    echo -e "${GREEN}从构建过程找到 ${#deploy_modules[@]} 个可部署模块${NC}"
  else
    # 检查 JAR 文件
    echo -e "${YELLOW}检查 JAR 文件...${NC}"
    deploy_modules=()
    jars_missing=false

    for module in "${MODULES[@]}"; do
      jar_files=($(find "./${module}/target" -name "*.jar" 2>/dev/null | grep -v "original"))

      if [ ${#jar_files[@]} -gt 0 ]; then
        deploy_modules+=("$module")
      else
        echo -e "${RED}✗ ${module}: 未找到 JAR 文件${NC}"
        jars_missing=true
      fi
    done

    if [ "$jars_missing" = true ]; then
      echo -e "${YELLOW}有些模块缺少 JAR 文件，只部署可用的 ${#deploy_modules[@]} 个模块${NC}"
    fi
  fi

  if [ ${#deploy_modules[@]} -eq 0 ]; then
    echo -e "${RED}错误: 没有可部署的模块，请先构建项目${NC}"
    exit 1
  fi

  # 确认启动服务
  echo -e "${YELLOW}准备使用 Docker Compose 启动服务...${NC}"
  echo -e "${YELLOW}将部署以下模块: ${deploy_modules[*]}${NC}"
  read -p "是否继续? (y/n): " confirm
  if [ "$confirm" != "y" ]; then
    echo -e "${RED}部署已取消${NC}"
    exit 0
  fi

  # 停止并移除现有容器
  echo -e "${YELLOW}停止并移除现有容器...${NC}"
  docker-compose down

  # 找出要部署的核心服务
  core_to_deploy=()
  for module in "${deploy_modules[@]}"; do
    if [[ " ${CORE_SERVICES[@]} " =~ " ${module} " ]]; then
      core_to_deploy+=("$module")
    fi
  done

  # 找出要部署的次要服务
  others_to_deploy=()
  for module in "${deploy_modules[@]}"; do
    if [[ ! " ${CORE_SERVICES[@]} " =~ " ${module} " ]]; then
      others_to_deploy+=("$module")
    fi
  done

  # 启动核心服务
  if [ ${#core_to_deploy[@]} -gt 0 ]; then
    echo -e "${YELLOW}正在启动核心服务: ${core_to_deploy[*]}${NC}"
    docker-compose up -d ${core_to_deploy[@]}

    # 等待核心服务启动
    echo -e "${YELLOW}等待核心服务启动...${NC}"
    sleep 10

    # 检查核心服务是否启动成功
    core_services_running=true
    for service in "${core_to_deploy[@]}"; do
      if docker ps | grep -q $service; then
        echo -e "${GREEN}✓ $service 服务已成功启动${NC}"
      else
        echo -e "${RED}✗ $service 服务启动失败${NC}"
        core_services_running=false
      fi
    done

    if [ "$core_services_running" = false ]; then
      echo -e "${RED}有核心服务启动失败，是否继续启动其他服务? (y/n): ${NC}"
      read -p "" continue_others
      if [ "$continue_others" != "y" ]; then
        echo -e "${RED}其他服务部署已取消${NC}"
        echo -e "${YELLOW}可以使用 '$0 logs [服务名]' 查看日志${NC}"
        return
      fi
    fi
  else
    echo -e "${YELLOW}没有核心服务可部署${NC}"
  fi

  # 启动其他服务
  if [ ${#others_to_deploy[@]} -gt 0 ]; then
    echo -e "${YELLOW}正在启动其他服务: ${others_to_deploy[*]}${NC}"
    docker-compose up -d ${others_to_deploy[@]}

    # 等待其他服务启动
    echo -e "${YELLOW}等待其他服务启动...${NC}"
    sleep 5

    # 检查其他服务是否启动成功
    for service in "${others_to_deploy[@]}"; do
      if docker ps | grep -q $service; then
        echo -e "${GREEN}✓ $service 服务已成功启动${NC}"
      else
        echo -e "${RED}✗ $service 服务启动失败${NC}"
      fi
    done
  else
    echo -e "${YELLOW}没有其他服务可部署${NC}"
  fi

  echo -e "${GREEN}部署完成${NC}"

  # 清理临时文件
  rm -f /tmp/available_modules.txt
}

# 检查服务状态
check_status() {
  echo -e "${BLUE}=== 服务状态 ===${NC}"

  echo -e "${YELLOW}基础设施服务:${NC}"
  for service in "${INFRA_SERVICES[@]}"; do
    if docker ps | grep -q $service; then
      echo -e "${GREEN}✓ $service 正在运行${NC}"
    else
      echo -e "${RED}✗ $service 未运行${NC}"
    fi
  done

  echo -e "\n${YELLOW}核心服务:${NC}"
  for service in "${CORE_SERVICES[@]}"; do
    if docker ps | grep -q $service; then
      container_id=$(docker ps | grep $service | awk '{print $1}')
      status=$(docker inspect --format='{{.State.Status}}' $container_id)
      health=$(docker inspect --format='{{if .State.Health}}{{.State.Health.Status}}{{else}}N/A{{end}}' $container_id)
      uptime=$(docker inspect --format='{{.State.StartedAt}}' $container_id)
      uptime=$(date -d "$uptime" '+%Y-%m-%d %H:%M:%S')

      echo -e "${GREEN}✓ $service${NC}"
      echo -e "  状态: $status | 健康: $health | 启动时间: $uptime"
    else
      echo -e "${RED}✗ $service 未运行${NC}"
    fi
  done

  echo -e "\n${YELLOW}次要服务:${NC}"
  for service in "${OTHER_SERVICES[@]}"; do
    if docker ps | grep -q $service; then
      container_id=$(docker ps | grep $service | awk '{print $1}')
      status=$(docker inspect --format='{{.State.Status}}' $container_id)
      health=$(docker inspect --format='{{if .State.Health}}{{.State.Health.Status}}{{else}}N/A{{end}}' $container_id)
      uptime=$(docker inspect --format='{{.State.StartedAt}}' $container_id)
      uptime=$(date -d "$uptime" '+%Y-%m-%d %H:%M:%S')

      echo -e "${GREEN}✓ $service${NC}"
      echo -e "  状态: $status | 健康: $health | 启动时间: $uptime"
    else
      echo -e "${RED}✗ $service 未运行${NC}"
    fi
  done
}

# 查看服务日志
view_logs() {
  service=$1

  if [ -z "$service" ]; then
    echo -e "${RED}错误: 请指定要查看日志的服务名称${NC}"
    echo -e "${YELLOW}示例: $0 logs doubao-gateway${NC}"
    return
  fi

  if docker ps | grep -q $service; then
    echo -e "${BLUE}=== $service 的日志 (Ctrl+C 退出) ===${NC}"
    docker-compose logs -f $service
  else
    echo -e "${RED}错误: $service 服务未运行${NC}"
  fi
}

# 主函数
main() {
  # 如果没有参数，显示欢迎信息和选项
  if [ $# -eq 0 ]; then
    echo -e "${BLUE}豆包云微服务一体化部署工具 v${VERSION}${NC}"
    echo -e "${YELLOW}请选择操作:${NC}"
    echo -e "  ${GREEN}1)${NC} 完整流程 (构建+部署)"
    echo -e "  ${GREEN}2)${NC} 只构建项目"
    echo -e "  ${GREEN}3)${NC} 只部署项目"
    echo -e "  ${GREEN}4)${NC} 初始化项目结构"
    echo -e "  ${GREEN}5)${NC} 检查服务状态"
    echo -e "  ${GREEN}6)${NC} 查看帮助"
    echo -e "  ${GREEN}0)${NC} 退出"

    read -p "请输入选项 [1-6]: " option

    case $option in
      1) cmd="all" ;;
      2) cmd="build" ;;
      3) cmd="deploy" ;;
      4) cmd="setup" ;;
      5) cmd="status" ;;
      6) cmd="help" ;;
      0) exit 0 ;;
      *)
        echo -e "${RED}无效选项${NC}"
        exit 1
        ;;
    esac
  else
    cmd=$1
  fi

  # 执行选择的命令
  case $cmd in
    build)
      check_environment "build"
      build_project
      ;;
    deploy)
      check_environment "deploy"
      check_infra_services
      deploy_project
      ;;
    all)
      check_environment "all"
      check_infra_services
      build_project
      deploy_project
      ;;
    setup)
      setup_project
      ;;
    status)
      check_status
      ;;
    logs)
      view_logs $2
      ;;
    help)
      show_help
      ;;
    *)
      echo -e "${RED}未知命令: $cmd${NC}"
      show_help
      exit 1
      ;;
  esac

  # 完成后显示服务地址
  if [[ "$cmd" == "deploy" || "$cmd" == "all" ]]; then
    echo -e "\n${YELLOW}服务访问地址:${NC}"
    echo -e "  网关: http://localhost:8001"
    echo -e "  授权服务: http://localhost:8081"
    echo -e "  用户服务: http://localhost:8082"
    echo -e "  设备服务: http://localhost:8083"
    echo -e "  聊天服务: http://localhost:8084"
    echo -e "  文件服务: http://localhost:8085"
    echo -e "  微信服务: http://localhost:8086"
    echo -e "  硬件服务: http://localhost:8087"
  fi
}

# 执行主函数
main "$@"